package util;

import exception.EncodingErrorException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author MissChen
 * @date 2024年05月14日 13:59
 */
public class CookieUtil {
    public static void addCookie(String name, String value, HttpServletResponse response) throws EncodingErrorException {
        try {
            Cookie cookie=new Cookie(name, URLEncoder.encode(value,"UTF-8"));
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            throw new EncodingErrorException("字符集有误");
        }
    }
    public static void addCookie(String name, String value,int maxAge, HttpServletResponse response) throws EncodingErrorException {
        try {
            Cookie cookie=new Cookie(name, URLEncoder.encode(value,"UTF-8"));
            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            throw new EncodingErrorException("字符集有误");
        }
    }
    public static void deleteCookie(String name,HttpServletResponse response) throws EncodingErrorException {
        addCookie(name,"",0,response);
    }
    public static void modifyCookie(String name,String value,HttpServletResponse response) throws EncodingErrorException {
        addCookie(name,value,response);
    }
    public static String findByName(String name, HttpServletRequest request) throws EncodingErrorException {
        Cookie[] cookies=request.getCookies();
        try {
            if(null!=cookies){
                for(Cookie cookie:cookies){
                    if(cookie.getName().equals(name)){
                        return URLDecoder.decode(cookie.getValue(),"UTF-8");
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new EncodingErrorException("字符集有误");
        }
        return null;
    }

}
